import { useRoutes, useNavigate, useLocation } from "react-router-dom";
import router from "@/router/index.jsx";
import { useEffect, useState } from "react";
import "./App.css";
function App() {
  const nav = useNavigate();
  const token = localStorage.getItem("token");
  useEffect(() => {
    if (!token) {
      nav("/login");
    }
  }, [token]);
  return (
    <div className="app">
      {/* {routes} */}
      <BeforeRouterEach />
    </div>
  );
}
function NavToLogin() {
  const nav = useNavigate();
  useEffect(() => {
    nav("/login");
  }, []);
  return <div></div>;
}
function NavToHome() {
  const nav = useNavigate();
  useEffect(() => {
    nav("/");
  }, []);
  return <div></div>;
}
// 前置路由守卫
function BeforeRouterEach() {
  const routes = useRoutes(router);
  const location = useLocation();
  const nav = useNavigate();
  useEffect(() => {
    const token = localStorage.getItem("token");
    if (location.pathname === "/login" && token) {
      nav("/");
      return <NavToHome></NavToHome>;
    }
    if (location.pathname !== "/login" && !token) {
      nav("/login");
      return <NavToLogin></NavToLogin>;
    }
  });

  return routes;
}

export default App;
